//% color="#1E90FF" iconWidth=50 iconHeight=40
namespace videoplay {
    //% block="播放视频[video_file] 方向[screen_rotation]" blockType="command"
    //% video_file.shadow="string" video_file.defl="video.mp4"
    //% screen_rotation.shadow="dropdown" screen_rotation.options="rotation"
    export function playvideo(parameter: any, block: any) {
        const funcId = "video_play";
        const file_path = parameter.video_file.code;
        const video_rotation = parameter.screen_rotation.code;
        Generator.addImport(`import cv2\nimport time\nimport sys`);
        Generator.addDeclaration("video_play", `
def video_play(video_path, rotation):
    max_fps=60
    vd = cv2.VideoCapture(video_path)
    if not vd.isOpened():
        print(f"无法打开视频文件: {video_path}")
        sys.exit(1)

    original_fps = vd.get(cv2.CAP_PROP_FPS)
    original_fps = original_fps if original_fps > 0 else 24
    target_fps = min(original_fps, max_fps)
    frame_delay = 1 / target_fps

    vd.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
    vd.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
    vd.set(cv2.CAP_PROP_BUFFERSIZE, 1)

    cv2.namedWindow('Video Player', cv2.WND_PROP_FULLSCREEN)
    cv2.setWindowProperty('Video Player', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

    ROTATION_MAP = {
        0: cv2.ROTATE_90_COUNTERCLOCKWISE,
        180: cv2.ROTATE_90_CLOCKWISE,
        270: cv2.ROTATE_180
    }

    last_frame_time = time.perf_counter()

    while True:
        time_diff = time.perf_counter() - last_frame_time
        if time_diff >= frame_delay:
            last_frame_time += frame_delay
            ret, frame = vd.read()
            if not ret: break
            
            if rotation != 90:
                frame = cv2.rotate(frame, ROTATION_MAP[rotation])
            cv2.imshow('Video Player', frame)

        remaining_time = frame_delay - (time.perf_counter() - last_frame_time)
        if remaining_time > 0:
            time.sleep(max(0, remaining_time * 0.5))

        if cv2.waitKey(1) & 0xFF == 27:
            break

    vd.release()
    cv2.destroyAllWindows()
`);
        // 生成执行代码
        Generator.addCode(`video_play(${file_path}, ${video_rotation})`);
    }
}
